package com.hrms.utils;

import com.hrms.constant.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static String signKey = "SVRIRUlNQQ==";
    private static Long expire = 7200000L; // 2小时

    /**
     * 生成JWT令牌
     * @return
     */
    public static String generateJwt(Map<String,Object> claims){
        String jwt = Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseJWT(String jwt){
        if(jwt.startsWith(Constants.TOKEN_PREFIX)){
            jwt = jwt.substring(7);
        }
        System.out.println(jwt);
        Claims claims = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }

    public static void main(String[] args) {
        Claims claims = parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJlbXBObyI6Nzg4OSwidXNlcm5hbWUiOiJpdHhoIiwiZXhwIjoxNzMyMTIzMzg5fQ.F6b6_r5rfCVwZzIoFcJuNWoImTo4vakthWynjB3vxh8");
        System.out.println(claims.get("empNo"));
    }
}
